#include"mystdio.h"
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<errno.h>
#include<stdlib.h>
#include<unistd.h>
#include<stdio.h>

myFILE* myFileOpen(const char* path, const char* mode)
{
    int fd = 0;
    int flag = 0;
    
    if(strcmp(mode, "r") == 0)
    {
        flag |= O_RDONLY;
    }
    else if(strcmp(mode, "w") == 0)
    {
        flag |= (O_WRONLY | O_CREAT | O_TRUNC);
    }
    else if(strcmp(mode, "a") == 0)
    {
        flag |= (O_CREAT | O_APPEND | O_WRONLY);
    }
    else 
    {
        // other 
    }

    // 不为0 表示文件不存在，需要给权限
    if((flag & O_CREAT) != 0)
    {
        fd = open(path, flag, 0666);
    }
    else 
    {
        fd = open(path, flag);
    }

    if(fd < 0)
    {
        errno = 2;
        return NULL;
    }

    myFILE* fp = (myFILE*)malloc(sizeof(myFILE));
    if(fp == NULL)
        return NULL;
    
    fp->_fileno = fd;
    // 
    fp->_end = 0;
    // 默认为行刷新
    fp->_flag = FLUSH_LINE;
    return fp;

}

int myFileClose(myFILE* stream)
{
    // 刷新缓冲区
    myFileFlush(stream);
    // 返回close的返回值
    return close(stream->_fileno);
}

int myFileFlush(myFILE* stream)
{
    if(stream->_end > 0)
    { 
        // 刷新工作本质上就是将数据从c语言文件缓冲区写入操作系统缓冲区
        write(stream->_fileno, stream->buffer, stream->_end);
        stream->_end = 0;
    }
    return 0;
}

int myFileWrite(const char* str, int num , myFILE* stream)
{
    memcpy(stream->buffer + stream->_end, str, num);
    stream->_end += num;

    // 判断是否需要刷新 是否遇到\n
    if((stream->_flag & FLUSH_LINE) && stream->_end > 0 && stream->buffer[stream->_end - 1] == '\n')
    {
        myFileFlush(stream);
    }
    // 返回写入的num个数
    return num;
}

